package com.hoas.api.encrypt.type.rsa;



import com.hoas.api.encrypt.type.Base64;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.security.*;
import java.util.HashMap;
import java.util.Map;

public class RSAGenPairUtil {

    private static final String KEY_ALGORITHM = "RSA";  
    
	/** 
     * 随机生成密钥对 
     */  
    public static Map<String,String> genKeyPair() {  
        // KeyPairGenerator类用于生成公钥和私钥对，基于RSA算法生成对象  
        KeyPairGenerator keyPairGen = null;  
        try {  
            keyPairGen = KeyPairGenerator.getInstance(KEY_ALGORITHM);  
        } catch (NoSuchAlgorithmException e) {  
            // TODO Auto-generated catch block  
            e.printStackTrace();  
        }  
        // 初始化密钥对生成器，密钥大小为96-1024位  
        keyPairGen.initialize(1024,new SecureRandom());  
        // 生成一个密钥对，保存在keyPair中  
        KeyPair keyPair = keyPairGen.generateKeyPair();  
        // 得到私钥  
        PrivateKey privateKey = keyPair.getPrivate();  
        // 得到公钥  
        PublicKey publicKey = keyPair.getPublic();  
        try {  
            // 得到公钥字符串  
            String publicKeyString = Base64.encode(publicKey.getEncoded());
            // 得到私钥字符串  
            String privateKeyString = Base64.encode(privateKey.getEncoded());  
              
            Map<String,String> keyPairResult = new HashMap<>();
            keyPairResult.put("privateKey", privateKeyString);
            keyPairResult.put("publicKey", publicKeyString);
            
            return keyPairResult;
            
        } catch (Exception e) {  
            e.printStackTrace();  
        }
		return null;  
    }
    
    /**
	 * 随机生成密钥对
	 */
	public static void genKeyPair(String filePath) {
		try {
			Map<String,String> keyPairs = genKeyPair();
			// 得到公钥字符串
			String publicKeyString = keyPairs.get("publicKey");
			// 得到私钥字符串
			String privateKeyString = keyPairs.get("privateKey");
			// 将密钥对写入到文件
			FileWriter pubfw = new FileWriter(filePath + "/publicKey.keystore");
			FileWriter prifw = new FileWriter(filePath + "/privateKey.keystore");
			BufferedWriter pubbw = new BufferedWriter(pubfw);
			BufferedWriter pribw = new BufferedWriter(prifw);
			pubbw.write(publicKeyString);
			pribw.write(privateKeyString);
			pubbw.flush();
			pubbw.close();
			pubfw.close();
			pribw.flush();
			pribw.close();
			prifw.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

    
}
